package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;

import com.sky.service.OrderService;
import com.sky.service.WebSocketServer;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.time.LocalDateTime;

import java.util.ArrayList;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    //订单详情表
    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private AddressBookMapper addressBookMapper;

    @Autowired
    private WebSocketServer webSocketServer;




    @Transactional
    @Override
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {
        //如果购物车为空,则抛出一个业务异常
        Long currentId = BaseContext.getCurrentId();   //查询当前用户id
        List<ShoppingCart> lists = shoppingCartMapper.selectByUserId(currentId);  //查询当前用户的购物车数据
        if (lists==null||lists.size()==0){
            throw new AddressBookBusinessException("购物车为空");
        }
        //如果地址为空,则抛出一个业务异常
        AddressBook addressBook= addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (addressBook==null){
            throw new AddressBookBusinessException("地址为空");
        }

        //创建一个订单对象,向订单表插入一条数据
        Orders order = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO,order);

        order.setOrderTime(LocalDateTime.now()); //设置下单时间
        order.setPayStatus(Orders.UN_PAID); //设置支付状态，提交订单后为未支付 。
        order.setStatus(Orders.PENDING_PAYMENT); //设置订单状态，待付款
        order.setNumber(String.valueOf(System.currentTimeMillis())); //设置订单号，使用当前时间戳
        order.setPhone(addressBook.getPhone()); //设置手机号
        order.setConsignee(addressBook.getConsignee()); //设置收货人
        order.setUserId(currentId); //当前订单的用户id
        orderMapper.insert(order);

        //向订单明细表插入多条数据
        List<OrderDetail> orderDetailList = new ArrayList<>();
        //遍历购物车数据,向订单明细表插入多条数据
        for (ShoppingCart shoppingCart : lists) {
            //向订单明细表插入一条数据
            OrderDetail orderDetail = new OrderDetail();//创建一个订单详情对象
            BeanUtils.copyProperties(shoppingCart,orderDetail); //将购物车数据复制到订单详情对象
            orderDetail.setOrderId(order.getId()); //设置订单id
            orderDetailList.add(orderDetail); //将订单详情对象添加到订单详情列表中
        }
        //向订单明细表插入多条数据
        orderDetailMapper.insertBatch(orderDetailList);
        //清空购物车数据
        shoppingCartMapper.deleteById(currentId);

        //封装VO对象
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder().
                id(order.getId()).orderTime(order.getOrderTime()).
                orderNumber(order.getNumber()).orderAmount(order.getAmount()).
                build();

        return orderSubmitVO;
    }
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        log.info("测试当前位置是否被调用，完成支付状态");
        // 当前登录用户id
        //Long userId = BaseContext.getCurrentId();
       // User user = userMapper.getById(userId);
        /*
        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );
        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        */
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code_url", "ORDERAIPAID");
        OrderPaymentVO  vo=jsonObject.toJavaObject(OrderPaymentVO.class); //将jsonObject转换为OrderPaymentVO对象
        Integer OrderPidStatus = Orders.PAID;  //订单支付状态,已支付
        Integer OrderStatus = Orders.TO_BE_CONFIRMED; //订单状态,待接单
        //为当前订单设置时间
        LocalDateTime check_out_time = LocalDateTime.now();
        //获取订单号
        String orderNumber = ordersPaymentDTO.getOrderNumber();

       //调用方法，修改订单状态
        orderMapper.updateStatus(OrderPidStatus,OrderStatus,check_out_time,orderNumber);
        // 调用方法，发送消息给客户端，前端接收json字符串，使用map封装之后，再使用fastjson将map转换为json字符串
        Map map = new HashMap();
        map.put("type", 1);//消息类型，1表示来单提醒
        map.put("content", "订单号：" + ordersPaymentDTO.getOrderNumber()); //订单号
        String jsonString = JSON.toJSONString(map);
        //通过WebSocket实现来单提醒，向客户端浏览器推送消息
        System.out.println(jsonString);
        webSocketServer.sendToAllClient(jsonString);

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        log.info("测试当前位置是否被调用，修改订单状态");
        // 根据订单号查询当前用户的订单
        Orders ordersDB = orderMapper.getByNumberAndUserId(outTradeNo, userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = new Orders();
        orders.setId(ordersDB.getId());//订单id
        orders.setStatus(Orders.TO_BE_CONFIRMED);
        orders.setPayStatus(Orders.PAID);
        orders.setCheckoutTime(LocalDateTime.now());
        orderMapper.update(orders);


    }

    @Override
    public OrderStatisticsVO statistics() {

        //查询订单，并统计订单数量，count函数
        // 根据状态，分别查询出待接单、待派送、派送中的订单数量
        Integer toBeConfirmed = orderMapper.countStatus(Orders.TO_BE_CONFIRMED);
        Integer confirmed = orderMapper.countStatus(Orders.CONFIRMED);
        Integer deliveryInProgress = orderMapper.countStatus(Orders.DELIVERY_IN_PROGRESS);
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
        orderStatisticsVO.setConfirmed(confirmed);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);
        return orderStatisticsVO;
    }

    @Override
    public PageResult pageQuery(OrdersPageQueryDTO ordersPageQueryDTO) {
        //分页插件
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());

        //查询订单
        Page<Orders> ordersList = orderMapper.pageQuery(ordersPageQueryDTO);
        //创建一个vo对象完成数据的封装
        ArrayList<OrderVO> orderVOS = new ArrayList<>();
        //查询订单详情,根据订单id查询订单详情
        for (Orders order : ordersList) {
            Long id = order.getId(); //获取订单id
            List<OrderDetail> orderDetail = orderDetailMapper.getByOrderId(id); //根据订单id查询订单详情
            //创建一个vo对象完成数据的封装
            OrderVO orderVO = new OrderVO();
            //添加订单地址，地址存放再地址表中，根据订单id查询地址表
            Long addressBookId = order.getAddressBookId();
            AddressBook addressBook = addressBookMapper.getById(addressBookId); //根据订单id查询地址表
            String addressDetail = addressBook.getDetail();//获取地址
            //将地址名保存到order表中
            order.setAddress(addressDetail); //将地址名保存到order表中
            BeanUtils.copyProperties(order,orderVO); //将订单数据复制到vo对象
         //获取菜品名字，
            String orderDishes = "";
            for (OrderDetail detailName : orderDetail) {
                String name = detailName.getName();
                orderDishes += name + " ,"; //将菜品名字拼接起来
            }
            orderDishes = orderDishes.substring(0,orderDishes.length()-1); //去掉最后一个逗号
            orderVO.setOrderDishes(orderDishes); //将菜品名字设置到vo对象
            //添加进入list
            orderVOS.add(orderVO); //将vo对象添加到list中
        }
        return new PageResult(ordersList.getTotal(),orderVOS);
    }

    @Override
    //更具订单号查询订单详情
    public OrderVO details(Long id) {

        Orders order = orderMapper.getId(id); //根据订单id查询订单信息
        //创建一个vo对象完成数据的封装
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(order,orderVO); //将订单数据复制到vo对象

        //根据订单id获取到订单详细信息
        List<OrderDetail> orderDetail = orderDetailMapper.getByOrderId(id); //根据订单id查询订单详情
        //将订单详情数据复制到vo对象
        orderVO.setOrderDetailList(orderDetail); //将订单详情数据复制到vo对象
        return orderVO;

    }

    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        //创建订单对象
        Orders orders = new Orders();
        //id信息设置
        orders.setId(ordersConfirmDTO.getId());
        //设置状态为接单
        orders.setStatus(Orders.CONFIRMED);
        //调用mapper进行update
        orderMapper.update(orders);


    }

    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) throws Exception {

        // 根据id查询订单，获取orders对象
        Orders ordersDB = orderMapper.getById(ordersRejectionDTO.getId());


        // 订单只有存在且状态为2（待接单）才可以拒单
        if (ordersDB == null || !ordersDB.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //查看当前订单支付状态，如果是已经支付需要退还
        Integer payStatus = ordersDB.getPayStatus(); //获取订单支付状态
        if (payStatus == Orders.PAID) {     //如果订单支付状态为已支付
            // 调用微信支付接口，申请退款
           // String refund = weChatPayUtil.refund(
                //    ordersDB.getNumber(),
                //    ordersDB.getNumber(),
                 //   new BigDecimal(0.01),
                 //   new BigDecimal(0.01));
            log.info("申请退款：已经注释");
        }
        //更新订单数据
        // 订单状态设置为已取消
        ordersDB.setStatus(Orders.CANCELLED);
        //补充退单说明
        ordersDB.setRejectionReason(ordersRejectionDTO.getRejectionReason());
        //取消时间
        ordersDB.setCancelTime(LocalDateTime.now());
        // 调用mapper完成数据库更新
        orderMapper.update(ordersDB);
    }

    @Override
    public void cancel(OrdersCancelDTO ordersCancelDTO) {
        // 根据id查询订单
        Orders ordersDB = orderMapper.getById(ordersCancelDTO.getId());
        //支付状态
        Integer payStatus = ordersDB.getPayStatus();
        if (payStatus == 1) {
            log.info("申请退款：");}

        // 管理端取消订单需要退款，根据订单id更新订单状态、取消原因、取消时间
        Orders orders = new Orders();
        orders.setId(ordersCancelDTO.getId());
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason(ordersCancelDTO.getCancelReason());
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);

    }

    @Override
    public void delivery(Long id) {
        // 根据id查询订单
        Orders ordersDB = orderMapper.getById(id);

        // 校验订单是否存在，并且状态为3
        if (ordersDB == null || !ordersDB.getStatus().equals(Orders.CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders orders = new Orders();
        orders.setId(ordersDB.getId());
        // 更新订单状态,状态转为派送中
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);

        orderMapper.update(orders);
    }

    /**
     * 完成订单
     *
     * @param id
     */
    @Override
    public void complete(Long id) {
        // 根据id查询订单
        Orders ordersDB = orderMapper.getById(id);

        // 校验订单是否存在，并且状态为4
        if (ordersDB == null || !ordersDB.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders orders = new Orders();
        orders.setId(ordersDB.getId());
        // 更新订单状态,状态转为完成
        orders.setStatus(Orders.COMPLETED);
        orders.setDeliveryTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    @Override
    /**
     * 用户端订单分页查询
     *
     * @param pageNum
     * @param pageSize
     * @param status
     * @return
     */
    public PageResult pageQuery4User(int pageNum, int pageSize, Integer status) {
        // 设置分页
        PageHelper.startPage(pageNum, pageSize);
        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        ordersPageQueryDTO.setStatus(status);

        // 分页条件查询
        Page<Orders> page = orderMapper.pageQuery(ordersPageQueryDTO);

        List<OrderVO> list = new ArrayList();

        // 查询出订单明细，并封装入OrderVO进行响应
        if (page != null && page.getTotal() > 0) {
            for (Orders orders : page) {
                Long orderId = orders.getId();// 订单id
                // 查询订单明细
                List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(orderId);
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                orderVO.setOrderDetailList(orderDetails);
                list.add(orderVO);
            }
        }
        return new PageResult(page.getTotal(), list);
    }

    @Override
    /**
     * 用户取消订单
     *
     * @param id
     */
    public void userCancelById(Long id) {
        // 根据id查询订单
        Orders ordersDB = orderMapper.getById(id);

        // 校验订单是否存在
        if (ordersDB == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        //订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
        if (ordersDB.getStatus() > 2) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders orders = new Orders();
        orders.setId(ordersDB.getId());

        // 订单处于待接单状态下取消，需要进行退款
        if (ordersDB.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            //调用微信支付退款接口

            //支付状态修改为 退款
            orders.setPayStatus(Orders.REFUND);
        }

        // 更新订单状态、取消原因、取消时间
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason("用户取消");
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    @Override
    public void repetition(Long id) {
        Long currentId = BaseContext.getCurrentId(); //获取当前用户id
        // 根据订单id查询当前订单详情
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(id);
        // 向购物车插入数据
        List<ShoppingCart> shoppingCartList = new ArrayList<>();
        for (OrderDetail orderDetail : orderDetailList) {
            ShoppingCart shoppingCart = new ShoppingCart();//用于存放每一条数据
            BeanUtils.copyProperties(orderDetail, shoppingCart);
            shoppingCart.setUserId(currentId);
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCartList.add(shoppingCart);
        }
        // 批量插入
        shoppingCartMapper.insertBatch(shoppingCartList);
    }

    @Override
    /**
     * 用户催单
     *
     * @param id
     */
    public void reminder(Long id) {
        // 查询订单是否存在
        Orders orders = orderMapper.getById(id);
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        //基于WebSocket实现催单
        Map map = new HashMap();
        map.put("type", 2);//2代表用户催单
        map.put("orderId", id);
        map.put("content", "订单号：" + orders.getNumber());
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }


}
